package com.yhy.wxzn.wcs.websocket;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import cn.hutool.core.util.StrUtil;
import com.yhy.wxzn.wcs.websocket.bean.FloorInfo;
import com.yhy.wxzn.wcs.websocket.bean.LiferInfo;
import com.yhy.wxzn.wcs.websocket.bean.NodeInfo;
import com.yhy.wxzn.wcs.websocket.bean.RgvInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.stereotype.Component;


@Slf4j
@ServerEndpoint(value = "/wcsWareHouseMonitor/{userId}/{type}", encoders = {ServerEncoder.class})
@Component
@Data
public class WareHouseMonitorWebSocketServer {

    private static ConcurrentHashMap<String,WareHouseMonitorWebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String,String> typeMap = new ConcurrentHashMap<>();

    private Session session;

    private String userId;

    private String type;

    //层或坐标ID
    private String param;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId,@PathParam("type") String type) {
        synchronized (WareHouseMonitorWebSocketServer.class){
            this.session = session;
            this.userId = userId;
            this.type = type;
            webSocketMap.put(getKey(userId,type),this);
            typeMap.put(type,type);
            log.info("wcsWareHouseMonitor有新的连接{}-{}",userId,type);
        }
    }

    private String getKey(String userId, String type) { return userId+type; }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        synchronized (WareHouseMonitorWebSocketServer.class){
            WareHouseMonitorWebSocketServer remove = webSocketMap.remove(getKey(userId, type));
            String type = remove.getType();
            for (String key : webSocketMap.keySet()) {
                WareHouseMonitorWebSocketServer wareHouseMonitorWebSocketServer = webSocketMap.get(key);
                if (wareHouseMonitorWebSocketServer.getType().equals(type))
                    return;
            }
            typeMap.remove(type);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String param) {
        this.param = param;
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object data) throws IOException, EncodeException {
        Result<Object> ok = Result.OK(data);
        this.session.getBasicRemote().sendObject(ok);
    }




    public static void sendRgvInfo() throws IOException, EncodeException {
        if (!typeMap.containsKey(WebSocketType.RGV_LIST.getType()))  return;
        List<RgvInfo> rgvInfos = RgvInfo.buildRgvInfos();
        for (String key : webSocketMap.keySet()) {
            WareHouseMonitorWebSocketServer server = webSocketMap.get(key);
            if (server.getType().equals(WebSocketType.RGV_LIST.getType())){
                server.sendMessage(rgvInfos);
            }
        }
    }


    public static void sendLifterInfo() throws IOException, EncodeException {
        if (!typeMap.containsKey(WebSocketType.RGV_LIST.getType()))  return;
        List<LiferInfo> liferInfos = LiferInfo.buildTestLiferInfos();
        for (String key : webSocketMap.keySet()) {
            WareHouseMonitorWebSocketServer server = webSocketMap.get(key);
            if (server.getType().equals(WebSocketType.LIFTER_LIST.getType())){
                server.sendMessage(liferInfos);
            }
        }
    }


    public static void sendFloorInfo() throws IOException, EncodeException {
        if (!typeMap.containsKey(WebSocketType.CURRENT_FLOOR.getType()))  return;

        for (String key : webSocketMap.keySet()) {
            WareHouseMonitorWebSocketServer server = webSocketMap.get(key);
            if (server.getType().equals(WebSocketType.CURRENT_FLOOR.getType())){
                String floor = server.getParam();
                if (StrUtil.isEmpty(floor))
                    continue;
                server.sendMessage(FloorInfo.buildFloorInfo(Integer.valueOf(floor)));
            }
        }
    }


    public static void sendNodeInfo() throws IOException, EncodeException {
        for (String key : webSocketMap.keySet()) {
            WareHouseMonitorWebSocketServer server = webSocketMap.get(key);
            if (server.getType().equals(WebSocketType.CURRENT_NODE.getType())){
                String nodeId = server.getParam();
                if (StrUtil.isEmpty(nodeId))
                    continue;
                server.sendMessage(NodeInfo.buildNodInfo(nodeId));
            }
        }
    }





}

